package com.xlh.dokka.svc.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 延迟任务监听器
 *
 * @author cheer
 */
@Component
@Slf4j
public class ImagePullListener implements ApplicationListener<ApplicationReadyEvent> {

    private static BlockingQueue<ImagePullTask> queue = new LinkedBlockingQueue<>();

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        new Thread(() -> {
            while (true) {
                try {
                    ImagePullTask imagePullTask = queue.take();
                    if (!imagePullTask.call()) {
                        queue.put(imagePullTask);
                    }
                    Thread.sleep(1000);
                } catch (Exception e) {
                    log.error("pull image exception", e);
                }
            }
        }).start();
    }

    public static void putTask(String ip, String imageName) {
        ImagePullTask imagePullTask = new ImagePullTask(ip, imageName);
        try {
            queue.put(imagePullTask);
        } catch (InterruptedException e) {
            log.warn("thread " + Thread.currentThread().getName() + " is interrupted");
        }
    }
}
